<?php
/*
* Copyright (c) 2010 by Cediti
*
* You may distribute under the terms of either the GNU Lesser General
* Public License or the new BSD License, as specified in the README file.
*/
// created :	19 March 2010
// version :	07/05/2010

class Cmis_Repository_Properties implements IteratorAggregate, Cmis_Render_Interface, Countable, Cmis_Repository_XmlResponseSetable
{
	/**
	 * @var array
	 */
	protected $_properties;

	public static $type = array(
		'propertyId',
		'propertyDateTime',
		'propertyString',
		'propertyInteger',
		'propertyBoolean',
	    '_external',
		'propertyDecimal'
	);

	const TYPE_ID = 0;
	const TYPE_DATE = 1;
	const TYPE_STRING = 2;
	const TYPE_INT = 3;
	const TYPE_BOOL = 4;
	const TYPE_EXTERNAL = 5;
	const TYPE_DECIMAL = 6;

	public function __construct()
	{
		$this->_init();
	}

	/**
	 * $xml should point on an entry node
	 * @see Cmis_Repository_XmlResponseSetable#setXmlResponse()
	 */
	public function setXmlResponse(SimpleXMLElement $xml, $prefix = '')
	{
		$prop = $xml->xpath('cmisra:object/cmis:properties');
		if (!empty($prop))
		{
			$properties = $prop[0]->children('cmis', true);

			foreach($properties as $propertyType => $property)
			{
				$attributes = $property->attributes();
				$this->set((string)$attributes['propertyDefinitionId'], $propertyType, $property->value, $attributes, $prefix);
			}
        }
	}

	public function count()
	{
		return count($this->_properties);
	}

	/**
	 * Get a property
	 * @param string $name the name of property
	 * @return object
	 */
	public function get($name)
	{
		return $this->_properties[ $name ];
	}

	/**
	 * Get all properties
	 * @return array
	 */
	public function getAll()
	{
		return $this->_properties;
	}

	/**
	 * Get only the extra values of a property
	 * @param string $name the property name
	 * @return array
	 */
	public function getExtras($name)
	{
		return $this->get($name)->getExtras();
	}

	/**
	 * Delete the current property entry
	 * @param string $name property name
	 * @return Cmis_Repository_Properties
	 */
	public function remove($name)
	{
		unset($this->_properties[ $name ]);
		return $this;
	}

	/**
	 * Set or replace an existing property 
	 * @see Cmis_Repository_Properties_Property#__construct()
	 * @return Cmis_Repository_Properties
	 */
	public function set($name, $type, $value, $extras = null, $prefix = '')
	{
		$property = new Cmis_Repository_Properties_Property($name, $type, $value, $extras, $prefix);
		$this->_properties[ $property->getName() ] = $property;

		return $this;
	}

	public function getIterator()
	{
		return new ArrayIterator($this->_properties);
	}

	public function render()
	{
		$rendered = '<cmis:properties>';
		foreach ($this as $property)
		{
			$rendered .= $property->render();
		}

		return $rendered . '</cmis:properties>';
	}

	protected function _init()
	{
		$this->_properties = array();
	}
}

# EOF
